﻿using HlELock.Core;
using HlELock.Core.Events;
using HlELock.Core.Models;
using HlELock.Domain;
using HlELock.Domain.Entities;
using HlELock.Modules.Hotel.Agency.Views;
using HlELock.Modules.Hotel.Main.Views;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace HlELock.Page.Views
{
    /// <summary>
    /// Login.xaml 的交互逻辑
    /// </summary>
    public partial class LoginPage : UserControl
    {
        private readonly IRegionManager _regionManager;
        public LoginPage(IRegionManager regionManager)
        {
            _regionManager = regionManager;



            InitializeComponent();
            if (PageSetting.IsHotel)
            {
                this.btnRegister.Visibility = Visibility.Visible;
                this.lblCompany.Visibility = Visibility.Visible;
                using (var context = new HlELockDbContext())
                {
                    var hotelInfo = context.HotelInfos.FirstOrDefault();
                    if (hotelInfo != null)
                    {
                        MyAppContext.HotelInfo = hotelInfo;
                        this.lblTitle.Content = hotelInfo.ProjectName;
                        this.lblCompany.Content = hotelInfo.CompanyName;

                    }
                }
            }
            else
            {
                this.lblTitle.Content = "经销商登录";
                this.btnRegister.Visibility = Visibility.Hidden;
                this.lblCompany.Visibility = Visibility.Hidden;
            }
#if DEBUG
            this.txtUserName.Text = PageSetting.IsHotel ? "123" : "test";
            this.txtPassword.Password = PageSetting.IsHotel ? "123" : "test";
#endif
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            var account = this.txtUserName.Text;
            var password = this.txtPassword.Password;

            if (string.IsNullOrWhiteSpace(account))
            {
                MessageBox.Show("请输入登录账号");
                return;
            }

            if (PageSetting.IsHotel)
            {
                using (var context = new HlELockDbContext())
                {
                    var hasUser = await context.LocalUsers.AnyAsync();
                    if (hasUser)
                    {
                        MyAppContext.CurrentUser = await context.LocalUsers.FirstOrDefaultAsync(f => f.Account == account && f.Password == password);
                        if (MyAppContext.CurrentUser == null)
                        {
                            MessageBox.Show("账号或密码错误");
                            return;
                        }
                        MyAppContext.HotelInfo = await context.HotelInfos.FirstOrDefaultAsync();
                        MyAppContext.Sector = MyAppContext.HotelInfo?.Sector;
                        _regionManager.RequestNavigate(RegionNames.HotelRegion, nameof(HotelMain));
                        EventBus.SetUserName(MyAppContext.CurrentUser.Name);

                    }
                    else
                    {
                        if (await LoginRequest())
                        {
                            MyAppContext.CurrentUser = new LocalUser
                            {
                                Account = account,
                                Password = password,
                                Name = account,
                                Role = LocaUserRole.管理员
                            };
                            context.Add(MyAppContext.CurrentUser);

                            MyAppContext.HotelInfo.Id = default;
                            context.Add(MyAppContext.HotelInfo);
                            await context.SaveChangesAsync();
                        }
                        else
                        {
                            return;
                        }

                    }
                }
            }
            else
            {
                if (await LoginRequest("agency"))
                {
                    _regionManager.RequestNavigate(RegionNames.HotelRegion, nameof(AgencyPage));

                }
                else
                {
                    return;
                }
            }



            async Task<bool> LoginRequest(string tenant = "")
            {
#if DEBUG
                var host = "http://60.204.173.108:10278";
#else
                var host = ConfigurationManager.AppSettings["host"];
#endif
                var loginUrl = $"{host}/client/login";

                var httpClient = new HttpClient();
                var postContent = new FormUrlEncodedContent(new Dictionary<string, string>()
                   {
                      {"Account",account },
                      {"Password", password},
                     {"Tenant",tenant }
                   });
                var response = await httpClient.PostAsync(loginUrl, postContent);
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var json = await response.Content.ReadAsStringAsync();
                    var jo = JObject.Parse(json);
                    MyAppContext.IsHotel = jo["IsHotel"].Value<bool>();

                    var userName = string.Empty;
                    if (MyAppContext.IsHotel)
                    {
                        MyAppContext.HotelInfo = JsonConvert.DeserializeObject<HotelInfo>(jo["Data"].ToString());

                        userName = MyAppContext.HotelInfo.CompanyName;
                    }
                    else
                    {
                        MyAppContext.AccessToken = jo["Data"]["Token"].ToString();
                        MyAppContext.Agency = JsonConvert.DeserializeObject<AgencyResponse>(jo["Data"]["Agency"].ToString());
                        MyAppContext.Sector = MyAppContext.Agency.Sector;
                        userName = MyAppContext.Agency.CompanyName;
                    }
                    EventBus.SetUserName(userName);
                    return true;
                }
                else
                {
#if DEBUG
                    MessageBox.Show(await response.Content.ReadAsStringAsync());
#else
        MessageBox.Show("登录失败，请检查账号或密码");
#endif
                    return false;
                }

            }

        }

        private void TextBlock_Click(object sender, RoutedEventArgs e)
        {
            var registerUrl = ConfigurationManager.AppSettings["registerUrl"];
            Process.Start(registerUrl);
        }

        private void Forget_TextBlock_Click(object sender, RoutedEventArgs e)
        {
            var forgetUrl = ConfigurationManager.AppSettings["forgetUrl"];
            Process.Start(forgetUrl);
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var cb = sender as ComboBox;
            var index = cb.SelectedIndex;
            ChangeLangue(index);
            var txt = AppHelper.GetResourceString("WangJiMiMa");

            if (btnForget != null)
                btnForget.Content = new TextBlock() { Text = txt };

            txt = AppHelper.GetResourceString("ZhuCeZhangHao");
            if (btnRegister != null)
                btnRegister.Content = new TextBlock() { Text = txt };

            txt = AppHelper.GetResourceString("YongFuMing");
            if (lblUser != null)
                lblUser.Content = txt;

            txt = AppHelper.GetResourceString("Password");
            if (lblPssword != null)
                lblPssword.Content = txt;
        }


        /// <summary>
        /// 修改语言 0:中文
        /// </summary>
        public static void ChangeLangue(int t)
        {
            var zh = "/HlELock.Page;component/Language/StringResource.zh-cn.xaml";
            var en = "/HlELock.Page;component/Language/StringResource.en-us.xaml";
            List<string> lst = new List<string>();
            if (t == 0)
            {
                lst.Add(zh);
                lst.Add(en);
            }
            else
            {
                lst.Add(en);
                lst.Add(zh);
            }
            if (Application.Current.Resources.MergedDictionaries[0].MergedDictionaries.Any(a => a.Source.OriginalString.Contains(lst[0])))
            {
                return;
            }
            else
            {
                Application.Current.Resources.MergedDictionaries[0].MergedDictionaries.Add(new ResourceDictionary
                {
                    Source = new Uri("pack://application:,,," + lst[0])
                });
            }

            var item = Application.Current.Resources.MergedDictionaries[0].MergedDictionaries.Where(w => w.Source.OriginalString.Contains(lst[1])).FirstOrDefault();
            if (item != null)
            {
                Application.Current.Resources.MergedDictionaries[0].MergedDictionaries.Remove(item);
            }

        }

        private void btnSetting_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}
